package com.pt.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("peer")
public class Peer implements Serializable {
    private static final long serialVersionUID = 1L;
    
    /**
     * Peer ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    
    /**
     * 种子ID
     */
    private Long torrentId;
    
    /**
     * 种子的info_hash
     */
    private String infoHash;
    
    /**
     * 用户ID
     */
    private Long userId;
    
    /**
     * Peer ID（十六进制字符串）
     */
    private String peerId;
    
    /**
     * IP地址
     */
    private String ip;
    
    /**
     * 端口
     */
    private Integer port;
    
    /**
     * 已上传量
     */
    private Long uploaded;
    
    /**
     * 已下载量
     */
    private Long downloaded;
    
    /**
     * 剩余量
     */
    @TableField("`left`")
    private Long left;
    
    /**
     * 是否为做种者
     */
    private Boolean seeder;
    
    /**
     * 最后活动时间
     */
    private LocalDateTime lastAction;
    
    /**
     * 客户端信息
     */
    private String userAgent;
    
    /**
     * 状态
     */
    private Integer status;
    
    /**
     * 最后汇报时间
     */
    private Long lastAnnounceTime;
    
    /**
     * 上传速度
     */
    private Long uploadSpeed;
    
    /**
     * 下载速度
     */
    private Long downloadSpeed;
    
    // 获取字节数组格式的peerId（如果需要）
    public byte[] getPeerIdBytes() {
        if (peerId != null) {
            return hexToBytes(peerId);
        }
        return null;
    }
    
    // 非数据库字段
    public String getStatusText() {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 0:
                return "已停止";
            case 1:
                return "下载中";
            case 2:
                return "做种中";
            default:
                return "未知";
        }
    }
    
    public String getProgress() {
        if (status == 2) { // 做种中
            return "100%";
        }
        long total = left + downloaded;
        if (total == 0) {
            return "0%";
        }
        return String.format("%.2f%%", (downloaded * 100.0) / total);
    }
    
    // 工具方法：十六进制字符串转字节数组
    private byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
} 